<template>
  <div>
    <div>
      <el-button type="primary" plain icon="Pointer" :disabled="multiple" @click="handleAssign()">指派</el-button>
      <!-- <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button> -->
      <el-button type="danger" plain icon="RefreshLeft" :disabled="multiple" @click="handleRedo()">重做</el-button>
    </div>
    <el-table
      height="calc(100vh - 360px)"
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
      :row-key="(row) => row.itemsId "
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="执行编号" align="center" prop="planId" />
      <el-table-column label="计划编号" align="center" prop="planId" />
      <el-table-column label="计划名称" align="center" prop="planName" />
      <el-table-column label="巡检路线" align="center" prop="routeName" />
      <el-table-column label="点编号" align="center" prop="spotId" />
      <el-table-column label="点名称" align="center" prop="spotName" />
      <el-table-column label="开始时间" align="center" prop="startTime" />
      <el-table-column label="结束时间" align="center" prop="endTime" />
      <el-table-column label="执行情况" align="center" prop="status">
        <template #default="scope">
          <span v-if="scope.row.status=='0'"> 待开始 </span>
          <span v-if="scope.row.status=='1'"> 按时完成 </span>
          <span v-if="scope.row.status=='2'"> 尚未完成 </span>
          <span v-if="scope.row.status=='3'"> 超时漏检 </span>
        </template>
      </el-table-column>
      <el-table-column label="巡检部门" align="center" prop="deptname" />
      <el-table-column label="巡检人员" align="center" prop="staffname" />
    </el-table>
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500" append-to-body @close="dialog.visible = false">
      <!-- 指派 -->
      <section v-if="dialog.mode === 'assign'">
        <el-row>
          <el-form ref="assignFormRef" :model="assignForm" label-width="150">
            <el-col>
              <el-form-item label="部门" prop="deptId" required>
                <el-tree-select
                  v-model="assignForm.deptId"
                  :data="deptOptions"
                  :props="{ value: 'id', label: 'label', children: 'children' }"
                  value-key="deptId"
                  placeholder="请选择部门"
                  check-strictly
                  default-expand-all
                  @node-click="handleNodeClick"
                />
              </el-form-item>
            </el-col>
            <el-col>
              <!-- to do 后期改成树结构 -->
              <el-form-item label="巡检人员:" prop="xjUserIds">
                <el-select v-model="assignForm.xjUserId" placeholder="请选择">
                  <el-option v-for="item in todolist" :key="item.userId" :label="item.nickName" :value="item.userId"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </section>
      <!--  重做-->
      <section v-if="dialog.mode === 'redo'">
        <el-row>
          <el-form :model="redoForm" ref="redoFormRef">
            <el-col>
              <el-form-item label="重做计划名称:" prop="planId">
                <el-select v-model="redoForm.planId" placeholder="请选择">
                  <el-option v-for="item in planSettingOptions" :key="item.planId" :label="item.planName" :value="item.planId"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="重做开始时间:" prop="startDate">
                <el-date-picker v-model="redoForm.startDate" type="date" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="重做结束时间:" prop="endDate">
                <el-date-picker v-model="redoForm.endDate" type="date" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="全部为合格:" prop="endDate"> 是：<el-checkbox v-model="redoForm.check" /> </el-form-item>
            </el-col>
          </el-form>
          <el-col style="font-size: 14px;">
            <p style="color: red; font-size: 15px;font-weight: bold;">您确定要重做计划执行么？</p>
            <p>1、计划的具体执行数据，是系统在前一日的23点自动生成的，计划调整后，如果不重做，当日及以前的执行数据不受任何影响。</p>
            <p>2、重做后，系统将删除指定计划在指定时间段内的执行数据，巡检记录信息是保持不变的。</p>
            <p>3、然后按照当前计划的设置参数，重新生成新的巡检计划执行数据，并重新统计漏检情况。</p>
            <p>4、只能重做最近30天的计划执行数据。</p>
          </el-col>
        </el-row>
      </section>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import api from '@/api/system/user';
import { ApiAssignTask, ApiReformPlan, ApiGetplanSituationList } from '@/api/inspection/inspectionplanSetting';
import { DeptVO } from '@/api/system/dept/types';
import { ApiGetInspectionplanSettingList } from '@/api/inspection/inspectionplanSetting';
import { userlist } from '@/api/inspection';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const props = defineProps({
  id: { type: [String , Number] , default: '' },
})
const loading = ref(false);
const params = ref({
  planId: '',
pageNum: 1,
pageSize: 10,
total: 0,
})
const todolist=ref<any>([])
const tableRef = ref<any>(null);
const addData = ref<any[]>([]);
  const single = ref(true);
const multiple = ref(true);
const ids = ref<string | number []>([]);
const dialog = ref({
  title: '指派',
  visible: false,
  mode: 'assign', // asign, redo
})
const deptOptions = ref<DeptVO[]>([]);
const planSettingOptions = ref<any[]>([])

const assignFormRef = ref<any>(null);
const redoFormRef = ref<any>(null);
const assignForm = ref({
  deptId: '',
  xjUserId: '',
})
const redoForm =ref({
  planId: '',
  startDate: '',
  endDate: '',
  check: '',
})

const buttonLoading = ref(false);

/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  const res = await api.deptTreeSelect();
  // deptOptions.value = res.data;
  deptOptions.value = res.data[0].children;
};
/** 查询执行人列表 */
const gettodoList = async (depId?:any) => {
  const res = await userlist({deptId:depId});
  todolist.value = res.rows;
};

const tableData = ref([]);
const emit = defineEmits(['closeDialog', 'getSelectData']);


const getList = async () => {
  loading.value = true;
  console.log("params",props.id)
  const res = await ApiGetplanSituationList({planId:props.id});
  console.log(res);
  tableData.value = res.rows;
  params.value.total = res.total;
  loading.value = false;
};
const handleNodeClick=(data:any)=> {
      console.log("datadata",data.id);
      gettodoList(data?.id)
}

const getInspectionplanSettingOptions = async () => {
  const res = await ApiGetInspectionplanSettingList({pageNum: 1, pageSize: 999});
  planSettingOptions.value = res.rows;
}

onMounted( async() => {
  await getInspectionplanSettingOptions();
  await getTreeSelect();
  await getList();
})

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map((item) => item.planId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const cancel = () => {
  dialog.value.visible = false;
}

const handleDelete = () => {

}
// 指派
const handleAssign = () => {
  dialog.value.mode = 'assign';
  dialog.value.title = '指派';
  assignForm.value.deptId = '';
  assignForm.value.xjUserId = '';
  dialog.value.visible = true;

}
// 重做
const handleRedo = () => {
  dialog.value.mode = 'redo';
  dialog.value.title = '重做';
  redoForm.value.planId = '';
  redoForm.value.startDate = '';
  redoForm.value.endDate = '';
  redoForm.value.check = '';
  dialog.value.visible = true;

}
const submitForm = () => {
  if (dialog.value.mode === 'assign') {
    assignFormRef.value?.validate(async (valid: boolean) => {
      if (!valid) return;
      console.log("assignForm",assignForm.value)
      buttonLoading.value = true;
      const object = {
        planId: props.id + '',
        xjDeptName: findLabelById(deptOptions.value, assignForm.value.deptId) || '',
        xjDeptId: assignForm.value.deptId + '',
        xjUserId: assignForm.value.xjUserId,
        xjUserName: todolist.value.find((item: any) => item.userId === assignForm.value.xjUserId)?.nickName || '',
      }
      await ApiAssignTask(object).finally(() => (buttonLoading.value = false));
      getList();
    })
  } else {
    redoFormRef.value?.validate(async (valid: boolean) => {
      if (!valid) return;
      console.log(redoForm.value)
      const obj = {
        planId: redoForm.value.planId,
        startDate : proxy?.parseTime(redoForm.value.startDate, '{y}-{m}-{d}'),
        endDate : proxy?.parseTime(redoForm.value.endDate, '{y}-{m}-{d}'),
        status: '0',
      }
    buttonLoading.value = true;
    await ApiReformPlan(obj).finally(() => (buttonLoading.value = false));
    getList();
    })
  }
}

const findLabelById = (tree: any[], id: string): any => {
    // 遍历当前节点的子节点
    for (let i = 0; i < tree.length; i++) {
        // 如果找到匹配的ID，则返回其label
        if (tree[i].id === id) {
            return tree[i].label;
        }

        // 如果当前节点有子节点，则递归查找
        if (tree[i].children && tree[i].children.length > 0) {
            const result = findLabelById(tree[i].children, id);
            if (result) {
                return result;
            }
        }
    }

    // 如果没有找到，返回null或undefined
    return null;
}
</script>
<style lang="scss" scoped>
:deep(.el-form-item__label) {
  font-size: 12px;
}
:deep(.el-table__cell) {
  padding: 0 !important;
}
.resume-label-width :deep(.el-descriptions--medium.is-bordered .el-descriptions-item__cell) {
    width: 159px;
  }
</style>
